package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.CrmDetial;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.CrmDao;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.utils.DateDialogUtil;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jrmf360.rylib.common.util.TimeUtils;
import com.jrmf360.rylib.common.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 项目反馈
 * Created by yangshijun on 2018/6/4.
 */

public class ProjectTrackingActivity extends AppCompatActivity {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.trackingEdit)
    EditText trackingEdit;
    @BindView(R.id.addattachment)
    TextView addattachment;
    @BindView(R.id.commui_time)
    TextView commuiTime;
    @BindView(R.id.r1)
    RadioButton r1;
    @BindView(R.id.r2)
    RadioButton r2;
    @BindView(R.id.radiogroup)
    RadioGroup radiogroup;
    @BindView(R.id.contact)
    EditText contact;
    @BindView(R.id.target)
    TextView target;
    @BindView(R.id.imageView3)
    ImageView imageView3;
    @BindView(R.id.cb_door)
    CheckBox cbDoor;
    @BindView(R.id.cb_call)
    CheckBox cbCall;
    @BindView(R.id.cb_decision)
    CheckBox cbDecision;
    @BindView(R.id.cb_key)
    CheckBox cbKey;
    @BindView(R.id.cb_submitproposal)
    CheckBox cbSubmitproposal;
    @BindView(R.id.cb_door_show)
    CheckBox cbDoorShow;
    @BindView(R.id.cb_submitcontract)
    CheckBox cbSubmitcontract;
    @BindView(R.id.cb_submitquote)
    CheckBox cbSubmitquote;
    @BindView(R.id.xcgt)
    View xcgt;
    @BindView(R.id.contract_time)
    TextView contractTime;
    @BindView(R.id.r3)
    RadioButton r3;
    @BindView(R.id.r4)
    RadioButton r4;
    @BindView(R.id.radiogroup2)
    RadioGroup radiogroup2;
    @BindView(R.id.submit)
    TextView submit;


    private String enterpriseCode;
    private String userId;
    private String userName;
    private CrmSearchBean.ListCrm  poBean;
    private String erpHttpUrl;
    private CrmDao crmDao;
    private String xcgztype_text;
    private String contract_time;
    private static final int GET_FUNNEL = 100;
    private ProjectTrackingActivity context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_crm_projecttracking);
        ButterKnife.bind(this);
        initData();
        context = this;
    }

    private void initData() {
        erpHttpUrl = LoginCache.getInstance().getLoginCache().getErpHttpUrl();
        poBean = (CrmSearchBean.ListCrm) getIntent().getSerializableExtra(SysConstant.msg_key_parcelable);
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        userName = LoginCache.getInstance().getUserDetaileInfo().getName();
        crmDao = new CrmDao(this);

        topBack.setVisibility(View.VISIBLE);
        topText.setText("项目跟踪反馈");

        String curTimeString = TimeUtils.getCurTimeString(new SimpleDateFormat("yyyy-MM-dd"));
        commuiTime.setText(curTimeString);
        initCrm(poBean.getAutoid()+"");
    }

    @OnClick({R.id.topBack, R.id.commui_time, R.id.target, R.id.xcgt, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.target:
//                CrmTrackingHelper trackingHelper = new CrmTrackingHelper(this, target, enterpriseCode);
//                trackingHelper.showState();
                startActivityForResult(new Intent(context, CrmGetFunnelActivity.class), GET_FUNNEL);
                break;
            case R.id.xcgt:

                DateDialogUtil dialogUtil1 = new DateDialogUtil(context, contractTime, 0, TimeUtils.getCurTimeMills());
                dialogUtil1.onCreateDialog().show();
                break;
            case R.id.commui_time:
                DateDialogUtil dialogUtil2 = new DateDialogUtil(context, commuiTime, TimeUtils.getCurTimeMills());
                dialogUtil2.onCreateDialog().show();
                break;
            case R.id.submit:
                feedBack();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK & requestCode == GET_FUNNEL) {
            String extra = data.getStringExtra(SysConstant.msg_key_string1);
            target.setText(extra);
        }
    }

    /**
     * 提交项目反馈
     */
    private void feedBack() {
        String tracking = trackingEdit.getText().toString().trim();
        if (TextUtils.isEmpty(tracking)) {
            ToastUtil.showNoWaitToast(context, "请输入反馈信息");
            return;
        }
        String commui_text = commuiTime.getText().toString().trim();
        if (TextUtils.isEmpty(commui_text)) {
            ToastUtil.showNoWaitToast(context, "请输入联系时间");
            return;
        }
        String contract_text = contact.getText().toString().trim();
        if (TextUtils.isEmpty(contract_text)) {
            ToastUtil.showNoWaitToast(context, "请输入联系人");
            return;
        }
        contract_time = contractTime.getText().toString().trim();
        if (TextUtils.isEmpty(contract_time)) {
            ToastUtil.showNoWaitToast(context, "下次沟通时间为必填");
            return;
        }

        StringBuilder deep1 = new StringBuilder();
        StringBuilder deep2 = new StringBuilder();
        if (cbCall.isChecked()) deep1.append("已电话,");
        if (cbDoor.isChecked()) deep1.append("已上门,");
        if (cbKey.isChecked()) deep1.append("见到关键人,");
        if (cbDecision.isChecked()) deep1.append("见到决策人,");

        if (cbDoorShow.isChecked()) deep2.append("上门演示,");
        if (cbSubmitproposal.isChecked()) deep2.append("提交方案,");
        if (cbSubmitquote.isChecked()) deep2.append("提交报价,");
        if (cbSubmitcontract.isChecked()) deep2.append("提交合同,");
        if (deep1.length() > 1) deep1.delete(deep1.length() - 1, deep1.length());
        if (deep2.length() > 1) deep2.delete(deep2.length() - 1, deep2.length());
        String gztype_text = r1.isChecked() ? "电话沟通" : "上门拜访";
        xcgztype_text = r3.isChecked() ? "电话沟通" : "上门拜访";

        //upCrmMedia(contract_text);

        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "SetCrmFQ");
        map.put("EnterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        map.put("employeename", userName);
        map.put("autoid", poBean.getAutoid()+"");
        map.put("gtinfo", tracking);
        map.put("gtdate", commui_text);
        map.put("gztype", gztype_text);
        map.put("lxr", contract_text);
        map.put("ldphase", target.getText().toString());
        map.put("gzsd", deep1.toString());
        map.put("sysd", deep2.toString());
        if (!TextUtils.isEmpty(contract_time)) {
            //下次拜访
            //crmVisit();
            map.put("xcgtdate", contract_time);
            map.put("xcgztype", xcgztype_text);
        }
        map.put("appCode","jyzs");
        map.put("appType","Android");
        map.put("appVersion","1.0.2");
        api.projectFeedBack(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.showNoWaitToast(context, "保存失败");
                    }

                    @Override
                    public void onNext(Object o) {
                        RceLog.d("lml", o.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(o.toString());
                            boolean result = jsonObject.getBoolean("result");
                            RceLog.d("lml", "result=" + result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        ToastUtil.showNoWaitToast(context, "保存成功");
                        finish();

                    }
                });
    }





    public void initCrm(String crmid) {
        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "InitCrmFQ");
        map.put("crmId", crmid);
        map.put("enterpriseCode",enterpriseCode);
        map.put("appCode","jyzs");
        map.put("appType","Android");
        map.put("appVersion","1.0.2");
        api.projectFeedBack(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        RceLog.d("lml", "onError=");
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(Object o) {
                        RceLog.d("lml", "onNext=" + o.toString());
                        Gson gson = new Gson();
                        String s = gson.toJson(o);
                        RceLog.d("lml", "onNext=" + s);
                        try {


                            JSONObject jsonObject = new JSONObject(s);
                            String gzsd = jsonObject.getString("gzsd");//跟踪深度
                            String ldphase = jsonObject.getString("ldphase");//漏斗状态
                            String gjsysd = jsonObject.getString("gjsysd");
                            if (ldphase != null & ldphase.length() > 0) {
                                target.setText(ldphase);
                            }
                            if (gzsd != null & gzsd.length() > 0) {
                                if (gzsd.contains("已电话")) cbCall.setChecked(true);
                                if (gzsd.contains("已上门")) cbDoor.setChecked(true);
                                if (gzsd.contains("见到关键人")) cbKey.setChecked(true);
                                if (gzsd.contains("见到决策人")) cbDecision.setChecked(true);
                            }
                            if (gjsysd != null & gjsysd.length() > 0) {
                                if (gjsysd.contains("上门演示")) cbDoorShow.setChecked(true);
                                if (gjsysd.contains("提交方案")) cbSubmitproposal.setChecked(true);
                                if (gjsysd.contains("提交报价")) cbSubmitquote.setChecked(true);
                                if (gjsysd.contains("提交合同")) cbSubmitcontract.setChecked(true);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * 上传CRM多媒体即时消息
     * @param contract_text
     */
    public void upCrmMedia(String contract_text) {
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        int processFlag = r1.isChecked() ? 1 : 2;
        map.put("method", "CrmDiscussMultimedia");
        map.put("enterpriseCode", enterpriseCode);
        map.put("userId", userId);
        map.put("name", userName);
        map.put("crmId", poBean.getAutoid()+"");
        map.put("text", contract_text);
        map.put("processFlag", processFlag + "");
        Log.i("test","参数："+map.toString());
        api.upCrmMedia(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            boolean result = jsonObject.getBoolean("result");
                            if (!result){
                                Log.e("err",jsonObject.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("test","错误：1");
                        e.printStackTrace();
                    }
                });
    }


    /**
     * CRM拜访
     */
    public void crmVisit() {
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "CrmProcess");
        map.put("crmId", poBean.getAutoid()+"");
        if (r3.isChecked()) {
            map.put("nextPhoneDt", contract_time);
        } else {
            map.put("nextVisitDt", contract_time);
        }
        Log.i("test","参数2："+map.toString());
        api.upCrmVisit(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            boolean result = jsonObject.getBoolean("result");
                            if (!result){
                                Log.e("err",jsonObject.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("test","错误：2");
                        e.printStackTrace();
                    }
                });
    }
}
